package im.oen.boot.common.utils;

import im.oen.boot.common.constant.Charsets;
import im.oen.boot.common.constant.OenCode;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;

/**
 * 摘要算法
 *
 * @author Kevin.Xu
 */
public class Digest {

    public static String MD5(String code) {
        try {
            byte[] btInput = code.getBytes(Charsets.UTF_8);
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            return ByteUtil.toHex(md);
        } catch (Exception e) {
            throw OenCode.DIGEST_ERROR.exception(e);
        }
    }

    public static String SHA1(String str) {
        return sha(str, "SHA1");
    }

    public static String SHA256(String str) {
        return sha(str, "SHA-256");
    }

    public static String SHA512(String str) {
        return sha(str, "SHA-512");
    }

    private static String sha(final String strText, final String strType) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(strType);
            messageDigest.update(strText.getBytes(Charsets.UTF_8));
            byte[] bytes = messageDigest.digest();
            return ByteUtil.toHex(bytes);
        } catch (Exception e) {
            throw OenCode.DIGEST_ERROR.exception(e);
        }
    }

    public static byte[] HMAC_SHA1(String source, String key) {
        return hmacSha(source.getBytes(Charsets.UTF_8), key.getBytes(Charsets.UTF_8), "HmacSHA1");
    }

    public static byte[] HMAC_SHA1(byte[] source, byte[] key) {
        return hmacSha(source, key, "HmacSHA1");
    }

    public static byte[] HMAC_SHA256(byte[] source, byte[] key) {
        return hmacSha(source, key, "HmacSHA256");
    }

    public static byte[] HMAC_SHA512(byte[] source, byte[] key) {
        return hmacSha(source, key, "HmacSHA512");
    }

    private static byte[] hmacSha(byte[] source, byte[] key, String type) {
        try {
            Mac hmacSHA1 = Mac.getInstance("HmacSHA1");
            SecretKeySpec macKey = new SecretKeySpec(key, "AES");
            hmacSHA1.init(macKey);
            return hmacSHA1.doFinal(source);
        } catch (Exception e) {
            throw OenCode.DIGEST_ERROR.exception(e);
        }
    }
}
